import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/UserLogin.vue'
import { useUserStore } from '@/stores/userStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/AppLayout.vue'),
      meta: { title: '文档生成', requiresAuth: true },
      redirect: '/document/create', // 默认重定向到文档生成页
      children: [
        {
          path: 'document/create',
          name: 'CreateDocument',
          component: () => import('@/views/document/CreateDocument.vue'),
          meta: { title: '生成文档', requiresAuth: true },
        },
        {
          path: 'document/list',
          name: 'TaskList',
          component: () => import('@/views/document/TaskList.vue'),
          meta: { title: '任务列表', requiresAuth: true },
        },
        // 你可以在这里添加其他页面路由
      ],
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/',
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  if (to.meta.requiresAuth) {
    const isAuthenticated = await userStore.checkAuth()
    if (!isAuthenticated) {
      next('/login')
      return
    }
  } else if (to.path === '/login') {
    const isAuthenticated = await userStore.checkAuth()
    if (isAuthenticated) {
      next('/')
      return
    }
  }

  next()
})

export default router
